package io.renren.modules.basedata.service.impl;

import cn.com.taiji.common.manager.net.http.binclient.ApiRequestException;
import cn.com.taiji.sdk.comm.LwClientHelper;
import cn.com.taiji.sdk.model.comm.protocol.cdts.passTransaction.*;
import io.renren.common.utils.GUID;
import io.renren.modules.basedata.dao.ExternalInvoiceUploadDao;
import io.renren.modules.basedata.dao.InternalInvoiceUploadDao;
import io.renren.modules.basedata.dao.OperlogDao;
import io.renren.modules.basedata.entity.tbl_ExternalInvoice;
import io.renren.modules.basedata.entity.tbl_InternalInvoice;
import io.renren.modules.basedata.entity.tbl_Operlog;
import io.renren.modules.basedata.service.ExternalInvoiceUploadService;
import io.renren.modules.basedata.service.InternalInvoiceUploadService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
public class ExternalInvoiceUploadServiceImpl implements ExternalInvoiceUploadService {
    private Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    ExternalInvoiceUploadDao externalInvoiceUploadDao;
    @Autowired
    OperlogDao operlogDao;


    @Override
    public String billUpload() throws Exception {

        log.info("开始获取发票基础数据信息！");
        int operResult = 0;
        List<tbl_ExternalInvoice> list = null;
        tbl_ExternalInvoice externalInvoice = null;
        tbl_Operlog operlog = new tbl_Operlog();
        list = getBillList();//获取发票基础数据信息
        Integer count =0;
        Long amount = 0L;

        if(list!=null&&list.size()>0){
            //发票基础数据信息上传及变更接口
            BillUploadRequest request = new BillUploadRequest();
            List<BillTransactionModel> listModelList = new ArrayList<BillTransactionModel>();
            for(int i=0;i<list.size();i++){
                externalInvoice = list.get(i);
                BillTransactionModel billTransactionModel  = new BillTransactionModel();
                billTransactionModel.setId(externalInvoice.getId());
                billTransactionModel.setCount(externalInvoice.getCount());
                billTransactionModel.setAmount(externalInvoice.getAmount());

                /** 此处应该将 details 封装成 List<BillRoadSplitDetail>   */
                String jsonDetails = externalInvoice.getRoadSplitDetail() ;
                List<BillRoadSplitDetail> modellist = new  ArrayList<BillRoadSplitDetail>();

                if(jsonDetails!=null || jsonDetails != ""){
                    //字符串转化为JSON数组对象
                    JSONArray jsonArray = JSONArray.fromObject(jsonDetails);
                    if(jsonArray!=null&&jsonArray.size()>0){
                        BillRoadSplitDetail model = new BillRoadSplitDetail();
                        for(int  n = 0; n <jsonArray.size(); n++){
                            JSONObject jsonObject = jsonArray.getJSONObject(n);
                            //为BillTransRoadSplitDetail对象赋值
                            model.setId(jsonObject.getString("id"));
                            model.setFee(jsonObject.getInt("fee"));
                            model.setSectionId(jsonObject.getString("sectionId"));
                            modellist.add(model);
                        }
                    }
                }
                billTransactionModel.setRoadSplitDetail(modellist);

                count = count+1;
                amount = amount+externalInvoice.getAmount();
            }
            request.setTollProvinceId(list.get(0).getTollProvinceId());
            request.setSerProvinceId(list.get(0).getSerProvinceId());
            request.setMessageId(456666L);
            request.setCount(count);
            request.setAmount(amount);
            request.setTransaction(listModelList);


            //获取发送文件名
            String fileName = request.getFileName();  //发送方编码（新疆--65）
            try{
                //指定响应的协议模型，调用upload发送数据
                BillUploadResponse response = LwClientHelper.binPostUrl(request);;
                log.info("上传发票基础数据信息成功，服务器返回："+response.toJson());
                if(response!=null&&response.getInfo().equals("成功！")){
                    //上传成功后逐条更新上传状态
                    for(int i=0;i<list.size();i++){
                        //更新上传标志

                        if(externalInvoiceUploadDao.updateExternalInvoice(list.get(i).getId())==1){
                            log.info("更新发票基础数据信息表上传标志成功!");
                            operResult = 1;
                            operlog = getOperlog(26,1,list.get(i).getId(),fileName,operResult, response.getInfo(),"上传成功，更新成功");
                        }else{
                            log.info("更新发票基础数据信息表上传标志成功!");
                            operlog = getOperlog(26,1,list.get(i).getId(),fileName ,operResult,response.getInfo(),"上传成功，更新失败");
                        }
                        operlogDao.insertlog(operlog);
                       // sqlMapClient.insert("operlog_ORACLE.insertlog",operlog);
                    }
                }else{
                    log.info("上传发票基础数据信息失败!失败原因："+response.getInfo());
                    externalInvoiceUploadDao.updateExternalInvoiceError(list.get(0).getId());
                    //sqlMapClient.update("transaction_ORACLE.updateExternalInvoiceError",list.get(0).getId());

                    //getOperlog（操作类型，传输类型，发送文件名，接收文件名，操作结果，部中心返回结果，说明）
                    operlog = getOperlog(26,1 ,list.get(0).getId(),fileName ,0,response.getInfo(), response.toJson());
                    operlogDao.insertlog(operlog);
                    // sqlMapClient.insert("operlog_ORACLE.insertlog",operlog);
                }
            }catch(IOException e){
                log.error("上传发票基础数据信息失败！错误信息："+e.getMessage());
                externalInvoiceUploadDao.updateExternalInvoiceError(list.get(0).getId());
               // sqlMapClient.update("transaction_ORACLE.updateExternalInvoiceError",list.get(0).getId());

                operlog = getOperlog(26, 1, list.get(0).getId(), fileName, 0,"IO异常", "出现IO异常，数据上传失败："+e.getMessage());
                operlogDao.insertlog(operlog);
                //sqlMapClient.insert("operlog_ORACLE.insertlog",operlog);
                e.printStackTrace();
            }catch (ApiRequestException apie) {
                log.error("上传发票基础数据信息失败！错误信息："+apie.getMessage());
                externalInvoiceUploadDao.updateExternalInvoiceError(list.get(0).getId());
               // sqlMapClient.update("transaction_ORACLE.updateExternalInvoiceError",list.get(0).getId());

                operlog = getOperlog(26, 1, list.get(0).getId(), fileName, 0,String.valueOf(apie.getErrCode()), "出现ApiRequestException异常，数据上传失败："+apie.getMessage());
                operlogDao.insertlog(operlog);
                // sqlMapClient.insert("operlog_ORACLE.insertlog",operlog);
                apie.printStackTrace();
            }
            return "上传发票基础数据信息结束！";
        }else{
            return "无发票基础数据信息，上传结束...";
        }

    }

    //获取发票基础数据信息
    @SuppressWarnings("unchecked")
    public List<tbl_ExternalInvoice> getBillList() throws IOException{
        List<tbl_ExternalInvoice> list;
        try{
            list = externalInvoiceUploadDao.getExternalInvoiceList();
            //list = sqlMapClient.queryForList("transaction_ORACLE.getExternalInvoiceList");
        }catch(Exception e){
            e.printStackTrace();
            log.error("获取发票基础数据信息失败！错误信息：",e);
            throw new IOException("获取发票基础数据信息失败:"+e.getMessage());
        }
        return list;
    }

    //获取operlog信息
    public tbl_Operlog getOperlog(int operType,int softType,String sendFileName,String reFileName,int operResult,String reResult, String content){
        tbl_Operlog operlog = new tbl_Operlog();
        operlog.setWastesn(new GUID().toString());
        operlog.setOperTime(new Date());
        operlog.setOpertype(operType);
        operlog.setSoftType(softType);
        operlog.setSendFileName(sendFileName);
        operlog.setReFileName(reFileName);
        operlog.setOperResult(operResult);
        operlog.setReResult(reResult);
        operlog.setContent(content);
        return operlog;
    }

}
